package com.beyond.pm.ui.login

import com.beyond.common.bean.UserBean
import com.beyond.common.manager.UserManager
import com.beyond.flow.container.Container
import com.beyond.flow.container.containers
import com.beyond.flow.inter.UiEvent
import com.beyond.flow.inter.UiState
import com.beyond.pm.base.BasicViewModel
import com.beyond.pm.bean.net.ReqLogin
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

/**
 * @author chen
 * @time 2023/6/1 12:42
 * @name ProjectManage
 * @class describe
 */
@HiltViewModel
class LoginViewModel @Inject constructor() :
    BasicViewModel() {

    private val _container by containers<LoginUiState, LoginUiEvent>(LoginUiState())
    val container: Container<LoginUiState, LoginUiEvent> = _container

//    init {
//        _container.updateState {
//            copy(
//                loadStatus = false
//            )
//        }
//    }

    fun dispatch(intent: LoginUiIntent) {
        when (intent) {
            is LoginUiIntent.Login -> {
                login(intent)
            }
        }
    }

    private fun login(intent: LoginUiIntent.Login) {
        val (phone, pwd) = intent
        requestLoading({ loginRepository.postLogin(ReqLogin(username = phone, password = pwd))}, {
            UserManager.user = UserBean(
                id = phone,
                phone = phone,
                token = it?.token
            )
            _container.sendEvent(LoginUiEvent.LoginSuccess)
        })
//        {
//            _container.sendEvent(LoginUiEvent.ErrorMessage("ERROR: $it"))
//            _container.updateState {
//                copy(
//                    loadStatus = false
//                )
//            }
//        }
    }
}

data class LoginUiState(
    val loginStatus: String = "",
//    val loadStatus: Boolean = false,
) : UiState

sealed class LoginUiEvent : UiEvent {
    object LoginSuccess : LoginUiEvent()
//    data class ErrorMessage(val message: String) : LoginUiEvent()
}

sealed class LoginUiIntent : UiEvent {
    //    object Login : LoginUiIntent()
    data class Login(val phone: String, val password: String) : LoginUiIntent()
}


